﻿using API.Models;
using Dapper;
using Files.Common;
using Files.Entity;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;

namespace API.Controllers
{
    //[EnableCors(origins: "*", headers: "*", methods: "*")]
    //[CustomActionFilterAttribute]
    public class MenuController : ApiController
    {
        /// <summary>
        /// 菜单信息
        /// </summary>
        /// <returns></returns>
        [HttpGet, HttpPost, Route("api/Menu/queryMenuList")]
        public IHttpActionResult queryMenuList(int? EventId, int? IdentityInformation)
        {

            //var eventId = WebHelper.GetSession("eventId");
            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                StringBuilder sb = new StringBuilder();
                if (IdentityInformation == 1)
                {
                    //参赛人员获取菜单
                    sb.AppendFormat("select m.Id,m.ParentId,m.Name,m.icon,m.IsParent,m.Url,m.OrderIndex,m.InsertTime,m.UpdateTime from ZX_Menus m join ZX_EventsAuthority e on m.Id=e.MenuId where e.EventsId={0}", EventId);
                }
                else
                {
                    //管理员获取全部菜单
                    sb.Append("select * from ZX_Menus");
                }
                var list = db.Query<ZX_Menus>(sb.ToString(), null).ToList();
                return Json(ToMenuJson(list, "0"));
            }
        }

        /// <summary>
        /// 所有菜单-无参数
        /// </summary>
        /// <returns></returns>
        [HttpGet, HttpPost, Route("api/Menu/queryAllmenu")]
        public IHttpActionResult queryAllmenu()
        {
            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from ZX_Menus");
                var list = db.Query<ZX_Menus>(sb.ToString(), null).ToList();
                return Json(ToMenuJson(list, "0"));
            }
        }

        private string ToMenuJson(List<ZX_Menus> data, string parentId)
        {
            StringBuilder sbJson = new StringBuilder();
            sbJson.Append("[");
            List<ZX_Menus> entitys = data.FindAll(t => t.ParentId == parentId);
            if (entitys.Count > 0)
            {
                foreach (var item in entitys)
                {
                    //string haschildren = item.IsParent == 1 ? "true" : "false";
                    string strJson = item.ToJson();
                    // strJson = strJson.Insert(strJson.Length - 1, ",\"hasChildren\":" + haschildren + "");
                    strJson = strJson.Insert(strJson.Length - 1, ",\"children\":" + ToMenuJson(data, item.Id) + "");
                    sbJson.Append(strJson + ",");
                }
                sbJson = sbJson.Remove(sbJson.Length - 1, 1);
            }
            sbJson.Append("]");
            return sbJson.ToString();
        }

        /// <summary>
        /// 根据Id查看菜单信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost, HttpGet, Route("api/Menu/queryMenuById")]
        public IHttpActionResult queryMenuById(string Id)
        {
            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("select  * from  ZX_Menus where Id='{0}'", Id);
                var list = db.Query<ZX_Menus>(sb.ToString(), null).ToList();
                var result = from m in list
                             select new
                             {
                                 m.Id,
                                 m.ParentId,
                                 m.icon,
                                 m.Name,
                                 m.IsParent,
                                 m.Url,
                                 m.OrderIndex,
                                 UpdateTime = m.UpdateTime.ToString("yyyy-MM-dd"),
                                 InsertTime = m.InsertTime.ToString("yyyy-MM-dd")
                             };
                return Json(new { data = result });
            }
        }

        /// <summary>
        /// /根据Id删除菜单信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost, HttpGet, Route("api/Menu/removeMenuById")]
        public IHttpActionResult removeMenuById([FromBody] JObject obj)
        {
            string Id = obj["Id"].ToString();
            Message ms = new Message();
            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                StringBuilder sb = new StringBuilder();
                var list = db.Query<ZX_Menus>(string.Format("select * from ZX_Menus where ParentId='{0}'", Id), null).ToList();
                if (list.Count > 0)
                {
                    ms.success = false;
                    ms.code = "0002";
                    ms.msg = "当前节点存在下级目录，请先删除下级目录";
                    ms.data = "";
                }
                else
                {
                    sb.AppendFormat("delete from  ZX_Menus  where Id='{0}'", Id);
                    var count = db.Execute(sb.ToString());
                    if (count > 0)
                    {
                        ms.success = true;
                        ms.code = "1111";
                        ms.msg = "删除成功";
                        ms.data = "";
                    }
                    else
                    {
                        ms.success = false;
                        ms.code = "0000";
                        ms.msg = "删除失败";
                        ms.data = "";
                    }

                }
                return Json(new { data = ms });
            }
        }

        /// <summary>
        /// 修改/添加菜单
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="ParentId"></param>
        /// <param name="Name"></param>
        /// <param name="icon"></param>
        /// <param name="IsParent"></param>
        /// <param name="Url"></param>
        /// <param name="OrderIndex"></param>
        /// <returns></returns>
        [HttpPost, HttpGet, Route("api/Menu/editMenu")]
        public IHttpActionResult editMenu([FromBody] JObject obj)
        {
            string Id = obj["Id"].ToString();
            string ParentId = obj["ParentId"].ToString();
            string Name = obj["Name"].ToString();
            string icon = obj["icon"].ToString();
            string IsParent = obj["IsParent"].ToString();
            string Url = obj["Url"].ToString();
            string OrderIndex = obj["OrderIndex"].ToString();
            //string Id, string ParentId, string Name, string icon, int IsParent, string Url, int OrderIndex
            Message ms = new Message();
            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                StringBuilder sb = new StringBuilder();

                if (Id == "0")
                {
                    Id = Guid.NewGuid().ToString().Replace("-", "");
                    sb.AppendFormat("insert into ZX_Menus(Id,ParentId,Name,icon,IsParent,Url,OrderIndex,InsertTime)values('{0}''{1}','{2}','{3}',{4},'{5}',{6},{7})", Id, ParentId, Name, icon, IsParent, Url, OrderIndex, DateTime.Now);
                }
                else
                {
                    sb.AppendFormat(@"update ZX_Menus set ParentId='{0}',Name='{1}',icon='{2}',IsParent={3},Url='{4}',OrderIndex={4},UpdateTime='{5}' where Id='{6}'", ParentId, Name, icon, IsParent, Url, OrderIndex, DateTime.Now);
                }
                var count = db.Execute(sb.ToString());
                if (count > 0)
                {
                    ms.success = true;
                    ms.code = "1111";
                    ms.msg = "操作成功";
                    ms.data = "";
                }
                else
                {
                    ms.success = true;
                    ms.code = "1111";
                    ms.msg = "操作失败";
                    ms.data = "";
                }
                return Json(new { data = ms });
            }
        }


    }

}